package com.example.homework.utils

import android.content.Context
import android.net.Uri
import android.util.Log
import com.example.homework.api.RetrofitInstance
import com.example.homework.model.User
import kotlinx.coroutines.runBlocking
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.io.InputStream
import com.example.homework.model.ApiResponse

object RankUtils {
    fun getUserData(context: Context): List<User> {
        return runBlocking {
            try {
                val api = RetrofitInstance.createApi(context)
                val response = api.getRankData()
                if (response.isSuccessful && response.body() != null) {
                    val apiResponse = response.body() as ApiResponse<List<User>>
                    if (apiResponse.code == 200) {
                        apiResponse.data.map { data ->
                            User(
                                account = data.account,
                                username = data.username,
                                avatar = data.avatar,
                                highScore = data.highScore
                            )
                        }
                    } else {
                        emptyList()
                    }
                } else {
                    emptyList()
                }
            } catch (e: Exception) {
                emptyList()
            }
        }
    }

    fun updateUser(user: User, context: Context): Boolean {
        return runBlocking {
            try {
                val api = RetrofitInstance.createApi(context)
                val response = api.updateUser(user)
                if (response.isSuccessful) {
                    true
                } else {
                    false
                }
            } catch (e: Exception) {
                false
            }
        }
    }

    suspend fun uploadImage(context: Context, imageUri: Uri): String? {
        val file = getFileFromUri(context, imageUri)
        val mimeType = getMimeTypeFromUri(context, imageUri)
        val requestFile = RequestBody.create(mimeType.toMediaType(), file)
        val body = MultipartBody.Part.createFormData("image", file.name, requestFile)

        return try {
            val api = RetrofitInstance.createApi(context)
            val response = api.uploadImage(body)
            if (response.isSuccessful && response.body() != null) {
                val apiResponse = response.body()!!
                if (apiResponse.code == 200) {
                    val imageUrl = apiResponse.data
                    Log.d("UploadImage", "Image URL: $imageUrl")
                    imageUrl
                } else {
                    Log.e("UploadImage", "Upload failed: ${apiResponse.msg}")
                    null
                }
            } else {
                Log.e("UploadImage", "Upload failed: ${response.code()} ${response.message()}")
                null
            }
        } catch (e: Exception) {
            Log.e("UploadImage", "Exception during upload: ${e.message}", e)
            null
        }
    }

    private fun getFileFromUri(context: Context, uri: Uri): File {
        val path = getPathFromUri(context, uri)
        return File(path)
    }

    private fun getMimeTypeFromUri(context: Context, uri: Uri): String {
        val mimeType = context.contentResolver.getType(uri)
        return mimeType ?: "application/octet-stream"
    }

    private fun getPathFromUri(context: Context, uri: Uri): String {
        if (uri.scheme == "content") {
            val inputStream: InputStream? = context.contentResolver.openInputStream(uri)
            val file = File(context.getExternalFilesDir(null), "temp_image.jpg")
            inputStream?.use { input ->
                file.outputStream().use { output ->
                    input.copyTo(output)
                }
            }
            return file.absolutePath
        } else if (uri.scheme == "file") {
            return uri.path!!
        } else {
            throw IllegalArgumentException("Unsupported URI scheme: ${uri.scheme}")
        }
    }
}